#include "mainwindow.h"
#include"users.h"
#include"signin.h"
#include "./ui_mainwindow.h"
#include "pathdialog.h"
#include <QInputDialog>

MainWindow::MainWindow(QString address,QWidget *parent,bool i)
    : currentAddress(address),QMainWindow(parent),ifsignin(i)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->nearButton->hide();
    ui->changeButton->hide();
    ui->startlabel->hide();
    ui->endlabel->hide();
    ui->endComboBox->hide();
    ui->startComboBox->hide();
    ui->userWidget->hide();
    ui->addpath->hide();
    ui->viaComboBox->hide();
    ui->startComboBox->addItem(currentAddress);
    ui->endComboBox->addItem(currentAddress);
    ui->startComboBox->setEditable(true);
    ui->endComboBox->setEditable(true);
    ui->viaComboBox->setVisible(false);     // 初始隐藏via下拉框
    ui->viaComboBox->setEditable(true);     // 设置为可编辑模式
     ui->viaComboBox->addItem(currentAddress);
    mapWidget = findChild<MapWidget*>("mapwidget");

    // 添加加载提示
    QLabel* loadingLabel = new QLabel(this);
    loadingLabel->setText("Generating map...");
    loadingLabel->setAlignment(Qt::AlignCenter);
    loadingLabel->setStyleSheet("font: 20px; color: white; background: rgba(0,0,0,150);");
    loadingLabel->setGeometry(0, 0, width(), height());
    loadingLabel->show();

    // 监听地图生成状态更新信号
    connect(&mapWidget->map, &Map::statusUpdate, this, [=](const QString& text) {
        loadingLabel->setText(text);
    });

    // 连接地图生成完成信号到初始化逻辑
    connect(mapWidget, &MapWidget::mapGenerationComplete, this, [=]() {
        loadingLabel->deleteLater();
        bool ok;
        int centerId = address.toInt(&ok);
        if (ok) mapWidget->map.setCurrentcenter(QString::number(centerId));
        mapWidget->update(); // 强制重绘
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}




void MainWindow::on_searchButton_clicked()
{
    // 获取输入框内容
    QString input = ui->posInput->text().trimmed(); // 去除首尾空格

    if (input.startsWith("Node")) {
        bool ok;
        int id = input.mid(4).toInt(&ok);
        if (ok) {
            QPointF pos = mapWidget->map.getVertexPosition(id);
            mapWidget->map.findNear(pos.x(), pos.y(), 100);
            mapWidget->update();
            return;
        }
    }

}


void MainWindow::on_returnButton_clicked()
{
    // 重置地图显示状态（显示所有边）
    mapWidget->map.resetDisplay();

    // 重置视图参数（中心点和缩放）
    mapWidget->zoomLevel = 1.0; // 直接访问成员变量
    mapWidget->centerX = 500;  // 默认中心
    mapWidget->centerY = 500;

    // 根据currentAddress重新定位中心（如果需要）
    bool ok;
    int centerId = currentAddress.toInt(&ok);
    if (ok) {
        QPointF pos = mapWidget->map.getVertexPosition(centerId);
        mapWidget->centerX = pos.x();
        mapWidget->centerY = pos.y();
    }

    // 立即重绘
    mapWidget->update();
}


void MainWindow::on_abnearestButton_clicked()
{
    ui->posInput->hide();
    ui->searchButton->hide();
    ui->mapwidget->show();
    ui->nearButton->show();
    ui->changeButton->show();
    ui->endlabel->show();
    ui->endComboBox->show();
    ui->startlabel->show();
    ui->startComboBox->show();
    ui->addpath->setVisible(true);  // 显示添加路径按钮
    ui->userWidget->hide();

}


void MainWindow::on_homeButton_clicked()
{
    ui->posInput->show();
    ui->searchButton->show();
    ui->mapwidget->show();

    ui->nearButton->hide();
    ui->changeButton->hide();
    ui->endlabel->hide();
    ui->endComboBox->hide();
    ui->startlabel->hide();
    ui->startComboBox->hide();
    ui->userWidget->hide();
    ui->viaComboBox->hide();
    ui->addpath->hide();
}


void MainWindow::on_changeButton_clicked()
{
    QString start=ui->startComboBox->currentText();
    QString end=ui->endComboBox->currentText();

    ui->startComboBox->setCurrentText(end);
    ui->endComboBox->setCurrentText(start);

}


void MainWindow::on_nearButton_clicked()
{
    QString start = ui->startComboBox->currentText().trimmed();
    QString end = ui->endComboBox->currentText().trimmed();
    QString via = ui->viaComboBox->currentText().trimmed();  // 途径点

    viaPoint = via; // 保存至成员变量

    // 添加新输入到下拉框中（去重略）
    ui->startComboBox->addItem(start);
    ui->endComboBox->addItem(end);

    QRegularExpression nodeRegex("^Node\\d+$");
    if (!nodeRegex.match(start).hasMatch() || !nodeRegex.match(end).hasMatch()) {
        QMessageBox::warning(this, "错误", "请输入有效的节点编号（如 Node123）");
        return;
    }

    // 提取 ID
    bool ok1, ok2, okVia = true;
    int startId = start.mid(4).toInt(&ok1);
    int endId = end.mid(4).toInt(&ok2);
    int viaId = -1;
    bool useVia = !via.isEmpty() && nodeRegex.match(via).hasMatch();
    if (useVia) viaId = via.mid(4).toInt(&okVia);
    if (!ok1 || !ok2 || (useVia && !okVia)) {
        QMessageBox::warning(this, "错误", "节点编号格式错误");
        return;
    }

    // 获取所有节点指针
    Vertex *startVertex = nullptr, *endVertex = nullptr, *viaVertex = nullptr;
    for (auto v : mapWidget->map.getVertices()) {
        if (v->id == startId) startVertex = v;
        if (v->id == endId) endVertex = v;
        if (useVia && v->id == viaId) viaVertex = v;
    }
    if (!startVertex || !endVertex || (useVia && !viaVertex)) {
        QMessageBox::warning(this, "错误", "起点/终点/途径点 不存在");
        return;
    }

    // 准备路径和距离
    std::vector<Edge*> fullPath;
    std::vector<Vertex*> pathNodes;
    std::vector<Vertex*> segmentStarts;
    double totalLength = 0.0;

    auto dijkstraFunc = showingTrafficPath ?
                            &Map::dijkstra : &Map::dijkstraByLength;

    auto getPath = [&](Vertex* src, Vertex* dst, std::vector<Edge*>& outPath) -> bool {
        std::unordered_map<Vertex*, double> dist;
        std::unordered_map<Vertex*, Edge*> prev;
        (mapWidget->map.*dijkstraFunc)(src, dist, prev);
        if (dist.find(dst) == dist.end()) return false;

        Vertex* current = dst;
        while (current != src) {
            if (prev.find(current) == prev.end()) break;
            Edge* edge = prev[current];
            outPath.push_back(edge);
            totalLength += edge->length;
            current = (edge->start == current) ? edge->end : edge->start;
        }
        std::reverse(outPath.begin(), outPath.end());
        return true;
    };

    if (useVia) {
        std::vector<Edge*> first, second;
        if (!getPath(startVertex, viaVertex, first) || !getPath(viaVertex, endVertex, second)) {
            QMessageBox::information(this, "提示", "存在不可达路径段（起点→途径点 或 途径点→终点）");
            return;
        }
        fullPath = first;
        fullPath.insert(fullPath.end(), second.begin(), second.end());
        segmentStarts = { startVertex, viaVertex };
    } else {
        if (!getPath(startVertex, endVertex, fullPath)) {
            QMessageBox::information(this, "提示", "起点与终点之间不可达");
            return;
        }
        segmentStarts = { startVertex };
    }

    // 保存路径节点顺序（用于方向判断）
    std::unordered_set<Vertex*> pathVertices;
    Vertex* current = segmentStarts.front();
    pathNodes.push_back(current);
    for (Edge* edge : fullPath) {
        Vertex* next = (edge->start == current) ? edge->end : edge->start;
        pathNodes.push_back(next);
        pathVertices.insert(edge->start);
        pathVertices.insert(edge->end);
        current = next;
    }

    mapWidget->map.pathVertexList = pathNodes;
    mapWidget->map.pathStart = startVertex;
    mapWidget->map.pathEnd = endVertex;
    mapWidget->map.visibleEdges = fullPath;
    mapWidget->map.currentNearVertices = std::vector<Vertex*>(pathVertices.begin(), pathVertices.end());
    mapWidget->map.showAllEdges = false;

    // 移动视角
    float midX = (startVertex->x + endVertex->x) / 2.0;
    float midY = (startVertex->y + endVertex->y) / 2.0;
    mapWidget->centerX = midX;
    mapWidget->centerY = midY;

    // 更新地图
    mapWidget->update();

    // 按钮状态切换
    showingTrafficPath = !showingTrafficPath;
    ui->nearButton->setText(showingTrafficPath ? "显示最短路径（仅按距离）" : "显示路况路径");

    // 弹窗显示路径
    PathDialog dialog(this, fullPath, totalLength, segmentStarts.front());  // 仍按旧接口传入起点
    dialog.setWindowTitle(useVia ? "路径详情（含途径点）" : "路径详情");
    dialog.exec();
}




void MainWindow::on_accountButton_clicked()
{
    if(!ifsignin)
    {
        signin *signInDialog = new signin(this);
        signInDialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(signInDialog, &signin::loginSuccess, this, &MainWindow::handleLoginSuccess);
        signInDialog->exec();
    }
    else{
        // 隐藏右侧其他组件
        ui->posInput->hide();
        ui->searchButton->hide();
        ui->returnButton->hide();
        ui->nearButton->hide();
        ui->changeButton->hide();
        ui->endlabel->hide();
        ui->endComboBox->hide();
        ui->startlabel->hide();
        ui->startComboBox->hide();
        ui->mapwidget->hide();

        // 显示用户信息组件
        ui->userWidget->show();
    }
}

// 处理登录成功
void MainWindow::handleLoginSuccess(QString phone, QString address) {
    // 更新用户信息标签
    ui->useridlabel->setText("账号："+phone);
    ui->useradlabel->setText("默认地址："+address);

    // 显示用户信息组件
    ui->userWidget->show();

    // 隐藏右侧其他组件
    ui->posInput->hide();
    ui->searchButton->hide();
    ui->returnButton->hide();
    ui->nearButton->hide();
    ui->changeButton->hide();
    ui->endlabel->hide();
    ui->endComboBox->hide();
    ui->startlabel->hide();
    ui->startComboBox->hide();
    ui->mapwidget->hide();

    ifsignin=true;

}


void MainWindow::on_resigninButton_clicked()
{
    // 弹出登录对话框
    signin *signInDialog = new signin(this);
    signInDialog->setAttribute(Qt::WA_DeleteOnClose);
    connect(signInDialog, &signin::loginSuccess, this, &MainWindow::handleLoginSuccess);
    signInDialog->exec();

}


void MainWindow::on_changeAddressButton_clicked()
{
    // 弹出输入对话框获取新地址
    bool ok;
    QString newAddress = QInputDialog::getText(this, tr("更改地址"),
                                               tr("请输入新地址（例如Node123）:"), QLineEdit::Normal,
                                               "", &ok);
    if (!ok || newAddress.isEmpty()) {
        return; // 用户取消或输入为空
    }

    // 验证地址格式
    QRegularExpression nodeRegex("^Node\\d+$");
    if (!nodeRegex.match(newAddress).hasMatch()) {
        QMessageBox::warning(this, "错误", "地址格式不正确，请输入类似Node123的格式");
        return;
    }

    // 获取当前用户手机号
    QString phoneLabel = ui->useridlabel->text();
    QString phone = phoneLabel.mid(3);

    // 更新用户数据文件中的地址
    if (User::updateAddress(phone, newAddress, "users.dat")) {
        currentAddress = newAddress; // 更新当前地址
        ui->useradlabel->setText(newAddress); // 更新界面显示

        // 更新startComboBox和endComboBox
        // 替换或添加新地址项
        int startIndex = ui->startComboBox->findText(currentAddress);
        if (startIndex != -1) {
            ui->startComboBox->setItemText(startIndex, newAddress);
        } else {
            ui->startComboBox->addItem(newAddress);
        }
        ui->startComboBox->setCurrentText(newAddress);

        int endIndex = ui->endComboBox->findText(currentAddress);
        if (endIndex != -1) {
            ui->endComboBox->setItemText(endIndex, newAddress);
        } else {
            ui->endComboBox->addItem(newAddress);
        }
        ui->endComboBox->setCurrentText(newAddress);

        QMessageBox::information(this, "成功", "地址已更新");
    } else {
        QMessageBox::warning(this, "错误", "地址更新失败");
    }
}


void MainWindow::on_addpath_clicked()
{ ui->viaComboBox->setVisible(true);      // 显示via下拉框
    ui->viaComboBox->setFocus();           // 获取焦点方便输入
    ui->viaComboBox->clearEditText();      // 清空原有文本（可选）

}


void MainWindow::on_viaComboBox_activated(int index)
{

}


void MainWindow::on_startComboBox_activated(int index)
{

}

